import { MobileLoginParam, UserInfo } from '@/service/api/type/user.type'
import { defineStore } from 'pinia'
import { LoginParam } from '../../service/api/type/user.type'
import { userAccountLogin, userMobileLogin } from '../../service/api/user'
import Message from '@/components/message/message'
import router from '@/router'
const userStore = defineStore({
  //id唯一且必填
  id: 'user',
  state: () => {
    return {
      // 存储登录人的信息
      profile: {
        id: '',
        account: '',
        mobile: '',
        token: '',
        avatar: '',
        nickname: '',
        gender: '',
        birthday: '',
        cityCode: '',
        provinceCode: '',
        profession: ''
      } as UserInfo
    }
  },

  // 开启数据缓存
  persist: {
    enabled: true
  },

  actions: {
    resetProfile() {
      this.$reset()
    },
    async accoutLogin(params: LoginParam) {
      const { result, msg } = await userAccountLogin(params)
      this.profile = result
      if (msg === '操作成功') {
        Message({
          text: '登录成功',
          type: 'success'
        })
        router.push('/')
      }
    },
    async phoneLogin(params: MobileLoginParam) {
      const { result, msg } = await userMobileLogin(params)
      this.profile = result
      if (msg === '操作成功') {
        Message({
          text: '登录成功',
          type: 'success'
        })
        router.push('/')
      }
    },
    logout() {
      this.$reset()
      router.push('/login')
    }
  }
})

export default userStore
